package web.java.demo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class FilterInvalidChar implements Filter{
	private List<String> invalidCharList;
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		//敏感词汇集合，在程序加载过程中便执行
		String value1="lala";
		String value2="邓小平";
		invalidCharList=new ArrayList<String>();
		invalidCharList.add(value1);
		invalidCharList.add(value2);
		System.out.println("初始化："+invalidCharList);
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest) arg0;
		request.setCharacterEncoding("utf-8");
		//接收前端发来的数据
		String content=request.getParameter("content");
		System.out.println("过滤器执行："+invalidCharList);
		//对数据进行处理
		if(content==null){
			arg2.doFilter(request,arg1);
			return;
		}
		for(String value:invalidCharList){
			if(content.contains(value)){
				content=content.replace(value,"****");
			}
		}
		request.setAttribute("content",content);
		//放行
		arg2.doFilter(request,arg1);
	}

}
